﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Excel;
using System.Text.RegularExpressions;

namespace Excel2Word
{
    public class ExcelReadHelper
    {

        Workbook activeWb = null;
        List<SourceElement> listEle = null;
        

        public ExcelReadHelper(Workbook targetWorkBook, List<SourceElement> listEle)
        {
            this.listEle = listEle;
            activeWb = targetWorkBook;
        }


        public Dictionary<string, Object> GetDataFromExcel()
        {

            Dictionary<string, Object> resultDic = new Dictionary<string, object>();
            foreach (SourceElement se in listEle)
            {
                if (se.filedType.Equals(SourceElement.FIELD_TYPE_NORMAL))
                {
                    if (se.locateType.Equals(ExcelInputHelper.ABSOLUTE_TYPE))
                    {
                        Worksheet ws = activeWb.Sheets[se.sheetName];
                        var va = ws.get_Range(se.fieldAddress).Value2.ToString();
                        resultDic[se.fieldName] = va;
                    }
                    else if (se.locateType.Equals(ExcelInputHelper.RELATIVE_TYPE))
                    {
                        Worksheet ws = activeWb.Sheets[se.sheetName];
                        var ra = ws.UsedRange.Find(se.fieldName);
                        var offsetDic = DecodeStr(se.locatePara);
                        var rowOffset = 0;
                        var colOffset = 0;
                        foreach (string keyStr in offsetDic.Keys)
                        {
                            if (keyStr.Equals("左") || keyStr.Equals("右"))
                            {
                                colOffset = keyStr.Equals("左") ? -offsetDic[keyStr] : offsetDic[keyStr];
                            }
                            else
                            {
                                rowOffset = keyStr.Equals("上") ? -offsetDic[keyStr] : offsetDic[keyStr];
                            }
                        }

                        resultDic[se.fieldName] = ra.get_Offset(rowOffset, colOffset).Value2.ToString();

                    }
                }

            }



            return resultDic;
        }



        public Dictionary<string,int> DecodeStr(string str)
        {
            var dic = new Dictionary<string, int>();
            Regex reg = new Regex(@"[\u4e00-\u9fa5](^\+|-)?\d+");
            var mcs = reg.Matches(str);

            foreach (Match mc in mcs)
            {
                var key = mc.Value.Substring(0, 1);
                var value = int.Parse(mc.Value.Substring(1));
                dic[key] = value;
            }

            return dic;
        }


    }
}
